var siteInfo = require('../siteinfo.js');
var endpoint = siteInfo.siteroot.split('/app/index.php');
var host = endpoint[0] + '/addons/zjhj_wdds/core/';

function req(url,data,method, cb, header = {}){
    var urlSeperator = url.indexOf('/');
    if (urlSeperator > 0) {
      var urlParams = url.split('/');
      url = '?m=Home&' + 'c=' + urlParams[0] + '&a=' + urlParams[1];
    }

    wx.request({
        url: host + url,
        data: data,
        method: method,
        header: header,
        success: function(res){
            if((urlParams[0] == 'products' || urlParams[0] == 'product_cates' || urlParams[0] == 'orders' || urlParams[0] == 'shops' || urlParams[0] == 'pay') && res.data.msg == 'shop_id.close.blank'){
                  wx.showToast({
                    title: '店铺已关闭',
                    image: '/images/fail.png',
                    duration: 2000
                  });
                  var pages = getCurrentPages()    //获取加载的页面
                  var url = pages[pages.length-1].route.split('/');

                if(url[1]=='shop'){
                    setTimeout(function(){ wx.redirectTo({ url: '/pages/index/home'})},2000);
                }
                return;
            }
            console.log(res);
            return typeof cb == "function" && cb(res.data)
        },
        fail: function(){
            return typeof cb == "function" && cb(false)
        }
    })
}
function upload(url, filePath, formData, cb, header = {}){
    var urlSeperator = url.indexOf('/');
    if (urlSeperator > 0) {
      var urlParams = url.split('/');
      url = '?m=Home&' + 'c=' + urlParams[0] + '&a=' + urlParams[1];
    }

    wx.uploadFile({
        url: host + url,
        filePath: filePath,
        name:'file',
        formData: formData,
        header: header,
        success: function(res){
            return typeof cb == "function" && cb(res.data)
        },
        fail: function() {
            return typeof cb == "function" && cb(false)
        }
    })
}
module.exports = {
  req: req,
  upload: upload
}
